package com.zyb.beiojbackendquestionservice.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.zyb.beiojbackendquestionservice.mapper.QuestionSubmitMapper;
import com.zyb.beiojbackendquestionservice.mq.MyMessageProducer;
import com.zyb.beiojbackendquestionservice.service.QuestionService;
import com.zyb.beiojbackendquestionservice.service.QuestionSubmitService;
import com.zyb.beiojbackendserviceclient.service.JudgeFeignClient;
import com.zyb.beiojcommon.common.ErrorCode;
import com.zyb.beiojcommon.constant.CommonConstant;
import com.zyb.beiojcommon.exception.BusinessException;
import com.zyb.beiojcommon.exception.ThrowUtils;
import com.zyb.beiojcommon.utils.SqlUtils;
import com.zyb.beiojmodel.model.dto.questionsubmit.QuestionSubmitAddRequest;
import com.zyb.beiojmodel.model.dto.questionsubmit.QuestionSubmitQueryRequest;
import com.zyb.beiojmodel.model.entity.Question;
import com.zyb.beiojmodel.model.entity.QuestionSubmit;
import com.zyb.beiojmodel.model.entity.User;
import com.zyb.beiojmodel.model.enums.QuestionSubmitLanguageEnum;
import com.zyb.beiojmodel.model.enums.QuestionSubmitStatusEnum;
import com.zyb.beiojmodel.model.mq.ExecuteCodeMessage;
import com.zyb.beiojmodel.model.vo.QuestionSubmitVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 *
 */
@Service
@Slf4j
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit>
        implements QuestionSubmitService {

    @Resource
    private QuestionService questionService;

    @Resource
    @Lazy
    private JudgeFeignClient judgeService;

    @Resource
    private MyMessageProducer myMessageProducer;


    /**
     * 提交
     *
     * @param questionSubmit
     * @param loginUser
     * @return
     */
    @Override
    public Long doQuestionSubmit(QuestionSubmitAddRequest questionSubmit, User loginUser) {
        Long questionId = questionSubmit.getQuestionId();
        // 判断题目是否存在
        Question question = questionService.getById(questionId);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //判断编程语言是否存在
        String language = questionSubmit.getLanguage();
        QuestionSubmitLanguageEnum languageEnum = QuestionSubmitLanguageEnum.getEnumByValue(language);
        ThrowUtils.throwIf(languageEnum == null,ErrorCode.PARAMS_ERROR,"不支持该编程语言");
        // 是否已提交
        long userId = loginUser.getId();
        //todo 初始情况先直接提交保存，后期再添加锁机制

        QuestionSubmit submit = new QuestionSubmit();
        submit.setQuestionId(questionId);
        submit.setCode(questionSubmit.getCode());
        submit.setUserId(userId);
        submit.setLanguage(language);

        submit.setStatus(QuestionSubmitStatusEnum.WAITING.getValue());
        submit.setJudgeInfo("{}");

        boolean save = save(submit);

        ThrowUtils.throwIf(!save,ErrorCode.SYSTEM_ERROR,"提交数据插入失败");

        //todo 要插入提交给判题服务的逻辑
        Long submitId = submit.getId();
//        CompletableFuture.runAsync(() -> {
//            judgeService.doJudge(submitId,userId);
//        });
        ExecuteCodeMessage executeCodeMessage = new ExecuteCodeMessage();
        executeCodeMessage.setQuestionSubmitId(submitId);
        executeCodeMessage.setUserId(userId);

        //通过消息队列将消息传递给判题服务
        log.info("题目服务发送消息：" + executeCodeMessage);
        myMessageProducer.sendMessage("code_exchange","my_routingKey", JSONUtil.toJsonStr(executeCodeMessage));
        return submitId;
    }

    /**
     * 封装了事务的方法
     *
     * @param userId
     * @param questionId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int doQuestionSubmitInner(long userId, long questionId) {
        QuestionSubmit questionSubmit = new QuestionSubmit();
        questionSubmit.setUserId(userId);
        questionSubmit.setQuestionId(questionId);
        QueryWrapper<QuestionSubmit> thumbQueryWrapper = new QueryWrapper<>(questionSubmit);
        QuestionSubmit oldQuestionSubmit = this.getOne(thumbQueryWrapper);
        boolean result;
        // 已提交
        if (oldQuestionSubmit != null) {
            result = this.remove(thumbQueryWrapper);
            if (result) {
                // 提交数 - 1
                result = questionService.update()
                        .eq("id", questionId)
                        .gt("thumbNum", 0)
                        .setSql("thumbNum = thumbNum - 1")
                        .update();
                return result ? -1 : 0;
            } else {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR);
            }
        } else {
            // 未提交
            result = this.save(questionSubmit);
            if (result) {
                // 提交数 + 1
                result = questionService.update()
                        .eq("id", questionId)
                        .setSql("thumbNum = thumbNum + 1")
                        .update();
                return result ? 1 : 0;
            } else {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR);
            }
        }
    }

    @Override
    public Wrapper<QuestionSubmit> getQueryWrapper(QuestionSubmitQueryRequest questionSubmitQueryRequest) {
        QueryWrapper<QuestionSubmit> queryWrapper = new QueryWrapper<>();
        if (questionSubmitQueryRequest == null) {
            return queryWrapper;
        }

        // 解构查询请求
        String language = questionSubmitQueryRequest.getLanguage();
        Integer status = questionSubmitQueryRequest.getStatus();
        Long questionId = questionSubmitQueryRequest.getQuestionId();
        Long userId = questionSubmitQueryRequest.getUserId();
        Date createTime = questionSubmitQueryRequest.getCreateTime();
        String sortField = questionSubmitQueryRequest.getSortField();
        String sortOrder = questionSubmitQueryRequest.getSortOrder();

        // 拼接查询条件
        queryWrapper.like(StringUtils.isNotBlank(language), "language", language);
        queryWrapper.like(ObjectUtils.isNotEmpty(QuestionSubmitStatusEnum.getEnumByValue(status)), "status", status);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        //日期的比较
        // 计算当天的开始时间（00:00:00）和结束时间（23:59:59）
        if (createTime!= null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date startDate = sdf.parse(sdf.format(createTime).substring(0, 10) + " 00:00:00");
                Date endDate = sdf.parse(sdf.format(createTime).substring(0, 10) + " 23:59:59");
                queryWrapper.between("createTime", startDate, endDate);
            } catch (ParseException e) {
                throw new RuntimeException("时间解析失败",e);

            }
        }
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    @Override
    public QuestionSubmitVO getQuestionSubmitVO(QuestionSubmit questionSubmit, HttpServletRequest request) {

        return QuestionSubmitVO.objToVo(questionSubmit);
    }

    @Override
    public Page<QuestionSubmitVO> getQuestionSubmitVOPage(Page<QuestionSubmit> questionSubmitPage, HttpServletRequest request) {
        List<QuestionSubmit> questionList = questionSubmitPage.getRecords();
        Page<QuestionSubmitVO> questionSubmitVOPage = new Page<>(questionSubmitPage.getCurrent(), questionSubmitPage.getSize(), questionSubmitPage.getTotal());
        if (CollectionUtils.isEmpty(questionList)) {
            return questionSubmitVOPage;
        }
        questionSubmitVOPage.setRecords(questionList.stream().map(questionSubmit -> {
            QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
            return questionSubmitVO;
        }).collect(Collectors.toList()));
        return questionSubmitVOPage;
    }


}




